package tk1.uebung3.ws;

import java.util.HashMap;
import java.util.List;

import javax.jws.WebService;

import tk1.uebung3.model.*;

@WebService(endpointInterface = "tk1.uebung3.ws.Shop")
public class ShopImpl implements Shop {
	
	//this is a cache as an alternative to ShoppingCartContainer.java in the model
	HashMap<String, ShoppingCart> idsToCarts = new HashMap<String, ShoppingCart>();
	
	@Override
	public String getCartId() {
		ShoppingCart newCart = new ShoppingCart();
		idsToCarts.put(newCart.getId(), newCart);
		ShoppingCartContainer.addShoppingCart(newCart);
		return newCart.getId();
	}

	@Override
	public String[] getProductTypes() {

		Assortment assortment = Assortment.getInstance();
		
		String[] result = new String[assortment.getProductTypes().size()];
		int i = 0;
		for(ProductType productType : Assortment.getInstance().getProductTypes()){
			result[i] = productType.getName();
			i++;
		}
		return result;
	}

	@Override
	public int getProductAmount(String productName) {
		ProductType productType = Assortment.getInstance().getProductTypeByName(productName);
		return productType.getAvailableAmount();
	}

	@Override
	public double getProductPrice(String productName) {
		ProductType productType = Assortment.getInstance().getProductTypeByName(productName);
		return productType.getPrice();
	}

	@Override
	public boolean purchaseProduct(String cartId, String productName, int amount) {
		ProductType productType = Assortment.getInstance().getProductTypeByName(productName);
		boolean success = productType.purchase(amount);
		if(success){
			ShoppingCart cart = idsToCarts.get(cartId);
			cart.addProduct(productType, amount);
		}
		return success;
		
	}

}
